package com.luying.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luying.dao.UserDao;
import com.luying.pojo.*;
import com.luying.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public int add(User user) throws Exception{
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("account",user.getAccount());
        List<User> users = userDao.selectByExample(example);
        if(users!=null&&users.size()>0){
            throw new Exception("账户名重复,请重新输入!");
        }
        return userDao.insertSelective(user);
    }

    @Override
    public int update(User user) {
        return userDao.updateById(user);
    }

    @Override
    public PageResult query(PageQuery pageQuery) {
        PageHelper.startPage(pageQuery.getPageIndex(),pageQuery.getPageSize());
        List<User> list =  userDao.selectPage(pageQuery);
        PageInfo<User> pageInfo = new PageInfo(list);
        PageResult pageResult = new PageResult(pageInfo.getTotal(),list);
        return pageResult;
    }

    @Override
    public User queryOne(Integer id) {
        return userDao.selectById(id);
    }

    @Override
    public int delete(Integer id) {
        return userDao.deleteById(id);
    }

    @Override
    public PageResult studentClassList(PageQuery pageQuery) {
        PageHelper.startPage(pageQuery.getPageIndex(),pageQuery.getPageSize());
        List<StudentInfo> studentInfos = userDao.studentClassList();
        PageInfo<StudentInfo> pageInfo = new PageInfo(studentInfos);
        PageResult pageResult = new PageResult(pageInfo.getTotal(),studentInfos);
        return pageResult;
    }

    @Override
    public void studentClassUpdate(Integer studentId, Integer classId) {
        int count = userDao.selectStudentClassByStudentId(studentId);
        if(count==0){
            userDao.insertStudentClass(studentId,classId);
        }else {
            userDao.updateStudentClass(studentId,classId);
        }
    }
}
